﻿using System;
using System.Linq;
using Microsoft.AspNetCore.Mvc;

namespace FlashPay.Admin.Controllers
{
    using FlashPay.EF.Models;
    using FlashPay.Entity;
    using FlashPay.Entity.Enum;
    using FlashPay.Entity.Parameter;
    using FlashPay.Entity.Request.Receipt;
    using FlashPay.Entity.Response.Payment;
    using FlashPay.Entity.Response.User;
    using FlashPay.Service.Interface;
    using FlashPay.Service.Interface.Receipt;
    using Microsoft.AspNetCore.Http;
    using System.Collections.Generic;

    /// <summary>
    /// 收款卡管理
    /// </summary>
    /// <remarks>2019-01-03 immi 添加</remarks>
    public class ReceiptController : BaseController
    {
        #region 注入
        /// <summary>
        /// 收款业务接口
        /// </summary>
        private readonly ReceiptService receiptService;

        /// <summary>
        /// 银行业务接口
        /// </summary>
        private readonly BankService _bankService;

        /// <summary>
        /// 银行卡业务接口
        /// </summary>
        private readonly BankCardService _bankCardService;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="_manage"></param>
        /// <param name="receiptService"></param>
        /// <param name="bankService"></param>
        public ReceiptController(IAuthenticate<TicketResponse> _manage, IHttpContextAccessor _accessor, ReceiptService receiptService, BankService bankService,BankCardService bankCardService) : base(_manage, _accessor)
        {
            this.receiptService = receiptService;
            this._bankService = bankService;
            this._bankCardService = bankCardService;
        }
        #endregion

        #region 收款卡
        /// <summary>
        /// 收款查询
        /// </summary>
        /// <param name="query">查询参数</param>
        /// <returns></returns>
        [AuthorizeFilter(AuthCode.ReceiptCard0001)]
        public JsonResult ReceiptCardQuery(PaymentCardQuery query)
        {
            var token = HttpContext.Request.Headers["token"];

            var ticketResponse = new TicketResponse();

            if (!string.IsNullOrEmpty(token))
            {
                ticketResponse = _manage.Get(token);
            }

            query.CardType = (sbyte)CardType.收款卡;
            query.CompanyId = ticketResponse.CompanyID;
            query.UserPermission = ticketResponse.UserPermission;
            var pager = this.receiptService.GetReceiptCard(query);
            return Json(pager);
        }


        /// <summary>
        /// 编辑收款卡
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [AuthorizeFilter(AuthCode.ReceiptCard0003)]
        public JsonResult ReceiptCardEdit(BankCard model)
        {
            var response = this._bankCardService.BankCardEditOther(model);
            return Json(response);
        }

        /// <summary>
        /// 编辑收款付
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [AuthorizeFilter(AuthCode.TransferCard0003)]
        public JsonResult TransferCardEdit(BankCard model)
        {
            var response = this._bankCardService.BankCardEditOther(model);
            return Json(response);
        }

        /// <summary>
        /// 获取收款卡
        /// </summary>
        /// <param name="bcId">银行卡编号</param>
        /// <returns></returns>
        [AuthorizeFilter(AuthCode.ReceiptCard0003)]
        public JsonResult GetReceiptCard(int bcId)
        {
            var response = _bankService.Get(_manage.data.CompanyID, bcId, _manage.data.UserPermission);

            return Json(response);
        }

        /// <summary>
        /// 更新状态
        /// </summary>
        /// <returns></returns>
        [AuthorizeFilter(AuthCode.ReceiptCard0004)]
        public JsonResult ReceiptCardUpdateStatus(int id, SByte status)
        {
            //输出
            var response = new JResult()
            {
                Success = false
            };

            //银行卡状态
            var enableStatus = new List<sbyte>()
            {
                (sbyte)EnableStatus.有效.GetHashCode(),
                (sbyte)EnableStatus.禁用.GetHashCode()
            };

            //验证参数是否包含在数组中
            if (enableStatus.Contains(status))
            {
                response = _bankService.UpdateEnableStatus(id, status, _manage.data.UserName);
            }
            else
            {
                response.ErrorMessage = "参数错误！";
            }


            return Json(response);
        }
        #endregion

        #region 收款记录
        //获取收款记录列表
        [AuthorizeFilter(AuthCode.ReceiptRecord0001)]
        public JsonResult GetReceiptRecord(PaymentRecordQuery query)
        {
            if (query.StartTime == null)
            {
                query.StartTime = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd 00:00:00");
            }
            else
            {
                query.StartTime = Convert.ToDateTime(query.StartTime).ToString("yyyy-MM-dd 00:00:00");
            }
            if (query.EndTime == null)
            {
                query.EndTime = DateTime.Now.ToString("yyyy-MM-dd 23:59:59");
            }
            else
            {
                query.EndTime = Convert.ToDateTime(query.EndTime).ToString("yyyy-MM-dd 23:59:59");
            }
            query.CompanyId = _manage.data.CompanyID;
            var pager = this.receiptService.GetReceiptRecordList(query);
            return Json(pager);
        }

        /// <summary>
        /// 获取收款记录
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        [AuthorizeFilter(AuthCode.ReceiptRecord0001)]
        public JsonResult GetReceiptRecords(DepositRecordQuery query)
        {

            var token = HttpContext.Request.Headers["token"];

            var ticketResponse = new TicketResponse();

            if (!string.IsNullOrEmpty(token))
            {
                ticketResponse = _manage.Get(token);
            }


            if (!string.IsNullOrEmpty(query.StartTime) && !string.IsNullOrEmpty(query.EndTime))
            {
                if (this.IsDate(query.StartTime) && this.IsDate(query.EndTime)){
                    query.StartTime = Convert.ToDateTime(query.StartTime).ToString("yyyy-MM-dd HH:mm:ss");
                    query.EndTime = Convert.ToDateTime(query.EndTime).ToString("yyyy-MM-dd HH:mm:ss");
                }else{
                    query.StartTime = DateTime.Now.ToString("yyyy-MM-dd 00:00:00");
                    query.EndTime = DateTime.Now.ToString("yyyy-MM-dd 23:59:59");
                }
            }else{
                query.StartTime = DateTime.Now.ToString("yyyy-MM-dd 00:00:00");
                query.EndTime = DateTime.Now.ToString("yyyy-MM-dd 23:59:59");
            }
            query.CompanyId = ticketResponse.CompanyID;
            query.UserPermission = ticketResponse.UserPermission;
            var pager = receiptService.GetReceiptRecord(query);
            return Json(pager);
        }

        /// <summary>
        /// 收款记录(导帮忙按钮)
        /// </summary>
        /// <returns>JResult</returns>
        [AuthorizeFilter(AuthCode.ReceiptRecord0001)]
        public JsonResult ReceiptRecordExportAuth()
        {
            var response = new JResult()
            {
                Success = true
            };

            try
            {
                var userPermission = _manage.data.UserPermission;
                if (userPermission.Contains("ReceiptRecord0004"))
                {
                    response.StatusCode = "ReceiptRecord0004";
                }
            }
            catch (Exception ex)
            {
                response.Success = false;
                response.ErrorMessage = ex.Message;
            }

            return Json(response);
        }

        /// <summary>
        /// 获取收款记录导出
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        [AuthorizeFilter(AuthCode.ReceiptRecord0001)]
        public JsonResult GetReceiptRecordsExport(DepositRecordQuery query)
        {
            var response = new JResult<List<DepositRecordResponse>>()
            {
                Success = false
            };

            //索引
            query.Page = 1;
            //页面
            query.Rows = 100000;

            if (!string.IsNullOrEmpty(query.StartTime) && !string.IsNullOrEmpty(query.EndTime))
            {
                if (this.IsDate(query.StartTime) && this.IsDate(query.EndTime))
                {
                    query.StartTime = Convert.ToDateTime(query.StartTime).ToString("yyyy-MM-dd HH:mm:ss");
                    query.EndTime = Convert.ToDateTime(query.EndTime).ToString("yyyy-MM-dd HH:mm:ss");
                }
                else
                {
                    query.StartTime = DateTime.Now.ToString("yyyy-MM-dd 00:00:00");
                    query.EndTime = DateTime.Now.ToString("yyyy-MM-dd 23:59:59");
                }
            }
            else
            {
                query.StartTime = DateTime.Now.ToString("yyyy-MM-dd 00:00:00");
                query.EndTime = DateTime.Now.ToString("yyyy-MM-dd 23:59:59");
            }
            query.CompanyId = _manage.data.CompanyID;
            query.UserPermission = _manage.data.UserPermission;
            
            try
            {
                var pager = receiptService.GetReceiptRecord(query);
                if (pager.Rows != null && pager.Rows.Any())
                {
                    var depositRecordResponse = new List<DepositRecordResponse>();

                    foreach (var item in pager.Rows)
                    {
                        depositRecordResponse.Add(new DepositRecordResponse() {
                            OrderNo = "'" + item.OrderNo,
                            CompanyName = item.CompanyName,
                            CompanyNameEn = item.CompanyNameEn,
                            WithdrawalOrderNo = item.WithdrawalOrderNo,
                            BankName = string.IsNullOrEmpty(item.BankName)?"": item.BankName,
                            CardName = string.IsNullOrEmpty(item.CardName) ? "" : item.CardName,
                            CardNumber = string.IsNullOrEmpty(item.CardNumber) ? "" : item.CardNumber,
                            WithdrawalAmount = item.WithdrawalAmount,
                            DepositDate = item.DepositDate,
                            WithdrawalAccountName = item.WithdrawalAccountName,
                            WithdrawalBankName = string.IsNullOrEmpty(item.WithdrawalBankName) ? "" : item.WithdrawalBankName,
                            WithdrawalCardNumber = string.IsNullOrEmpty(item.WithdrawalCardNumber) ? "" : "'" + item.WithdrawalCardNumber,
                            NoticeStatus = item.NoticeStatus,
                            NoticeStatusString = GetNoticeStatus(item.NoticeStatus),
                            NoticeLastDate = string.IsNullOrEmpty(item.NoticeLastDate)?"": item.NoticeLastDate,
                            NoticeTimes = item.NoticeTimes,
                            DepositType = item.DepositType,
                            PostScript = string.IsNullOrEmpty(item.PostScript) ? "" : item.PostScript,
                            TransType = item.TransType,
                            //ConfirmStatus = item.ConfirmStatus,
                            CreateDbdate = item.CreateDbdate,
                            DepositRemark = item.DepositRemark,
                            TimeDifference = item.TimeDifference,
                            ReadDate = item.ReadDate,
                            MakeUpPermission = item.MakeUpPermission
                        });
                    }
                    response.Data = depositRecordResponse;
                }
                response.StatusCode = $"收款记录({query.StartTime}-{query.EndTime})";
                response.Success = true;
            }
            catch (Exception ex) {
                response.SuccessMessage = ex.Message;
            }

            return Json(response);
        }

        /// <summary>
        /// 通知状态(未通知 = 1，通知成功 = 2，通知失败 = 3，通知中 = 4，不通知 = 5)
        /// </summary>
        /// <param name="status"></param>
        /// <returns></returns>
        private string GetNoticeStatus(sbyte status)
        {
            var result = "";

            switch (status)
            {
                case 1:
                    result = "<span style=font-weight: bold>未通知</span>";
                    break;
                case 2:
                    result = "<span style=color:#3e8f3e>通知成功</span>";
                    break;
                case 3:
                    result = "<span style=color:#FF0000>通知失败</span>";
                    break;
                case 4:
                    result = "<span style=font-weight: bold>通知中</span>";
                    break;
                case 5:
                    result = "<span style=font-weight: bold>不通知</span>";
                    break;
                default:
                    result = "无";
                    break;
            }

            return result;
        }

        /// <summary>
        /// 确认状态(未处理 = 1，自动审核通过 = 2，人工审核通过 = 3，人工审核拒绝 = 4)
        /// </summary>
        /// <param name="status"></param>
        /// <returns></returns>
        private string GetConfirmStatus(sbyte status)
        {
            var result = "";

            switch (status)
            {
                case 1:
                    result = "未处理";
                    break;
                case 2:
                    result = "自动审核通过";
                    break;
                case 3:
                    result = "人工审核通过";
                    break;
                case 4:
                    result = "人工审核拒绝";
                    break;
                case 5:
                    result = "不通知";
                    break;
                default:
                    result = "无";
                    break;
            }

            return result;
        }

        private bool IsDate(string date)
        {
            try
            {
                DateTime.Parse(date);
                return true;
            }
            catch
            {
                return false;
            }
        }

        //获取收款记录列表
        public JsonResult GetReceiptRecordByTime(string time, int minutes)
        {
            var response = new JResult()
            {
                Success = false
            };
            if (string.IsNullOrEmpty(time))
            {
                response.ErrorMessage = "时间获取出错";
                return Json(response);
            }
            PaymentRecordQuery q = new PaymentRecordQuery();
            q.StartTime = time;
            q.EndTime = Convert.ToDateTime(time).AddMinutes(minutes).ToString("yyyy-MM-dd HH:mm:ss");
            q.CompanyId = _manage.data.CompanyID;
            q.Type=1;
            var pager = this.receiptService.GetReceiptRecordList(q);
            return Json(pager);
        }

        /// <summary>
        /// 重置
        /// </summary>
        /// <param name="orderNo">订单编号</param>
        /// <returns></returns>
        [AuthorizeFilter(AuthCode.ReceiptRecord0002)]
        public JsonResult ResetNoticeStatus(Int64 orderNo)
        {
            var response = this.receiptService.ResetNoticeStatus(orderNo);

            return Json(response);
        }

        /// <summary>
        /// 收款匹配记录(补推送)
        /// </summary>
        /// <param name="orderNo">订单编号</param>
        /// <returns></returns>
        //[AuthorizeFilter(AuthCode.ReceiptRecord0002)]
        public JsonResult ReceiptMatchMakeUp(ReceiptMatchMakeUpRequest request)
        {
            var response = this.receiptService.ReceiptMatchMakeUp(request);

            return Json(response);
        }

        /// <summary>
        /// 收款记录[重置]
        /// </summary>
        /// <param name="request"></param>
        [AuthorizeFilter(AuthCode.ReceiptRecord0003)]
        public JsonResult MakeUp(long orderNo)
        {
            var para = new MakeUpRequest() {
                OrderNo = orderNo,
                UserPermission = _manage.data.UserPermission
            };
            var response = this.receiptService.MakeUp(para);

            return Json(response);
        }

        /// <summary>
        /// 改变公司
        /// </summary>
        /// <param name="request"></param>
        [AuthorizeFilter(AuthCode.ReceiptRecord0005)]
        public JsonResult ChangeCompany(ChangeCompanyRequest request)
        {
            request.LoginCompanyId = _manage.data.CompanyID;
            var response = receiptService.ChangeCompany(request);


            return Json(response);
        }
        #endregion
    }
}